#!/usr/bin/python
# coding=utf-8
import time
import rospy
import cv2 as cv
import numpy as np
from geometry_msgs.msg import Twist
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
from std_msgs.msg import Int8


class image_converter:
    def __init__(self):
        self.cmd_pub = rospy.Publisher(
            "/cmd_vel", Twist, queue_size=10)			# 发布运动控制信息
        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber(
            "/usb_cam/image_raw", Image, self.imageCallback)

    def imageCallback(self, data):
        try:
            cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8")			# 获取订阅的摄像头图像
        except CvBridgeError as e:
            print e
        # cv.imshow("Original_Image", cv_image)

        # 对图像进行处理
        kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))		# 定义结构元素
        height, width = cv_image.shape[0:2]
        screen_center = width / 2
        screen_center_h = height / 2

        offset = 50
        offset_h = 30
        lower_b = (35, 43, 46)
        upper_b = (77, 255, 255)

        hsv_frame = cv.cvtColor(cv_image, cv.COLOR_BGR2HSV)				# 转成HSV颜色空间
        mask = cv.inRange(hsv_frame, lower_b, upper_b)
        if len(mask) > 0:
            mask2 = cv.morphologyEx(mask, cv.MORPH_OPEN, kernel)			# 开运算去噪
            mask3 = cv.morphologyEx(mask2, cv.MORPH_CLOSE, kernel)			# 闭运算去噪
            # cv.imshow("mask", mask3)

            # 找出面积最大的区域
            _, contours, _ = cv.findContours(
                mask3, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
            maxArea = 0
            maxIndex = 0
            for i, c in enumerate(contours):
                area = cv.contourArea(c)
                if area > maxArea:
                    maxArea = area
                    maxIndex = i
            # 绘制轮廓
            cv.drawContours(cv_image, contours, maxIndex, (255, 255, 0), 2)

            # 获取外切矩形
            x, y, w, h = cv.boundingRect(contours[maxIndex])
            cv.rectangle(cv_image, (x, y), (x + w, y + h), (255, 0, 0), 2)
            # 获取中心像素点
            center_x = int(x + w / 2)
            center_y = int(y + h / 2)
            cv.circle(cv_image, (center_x, center_y), 5, (0, 0, 255), -1)

            rect = cv.minAreaRect(contours[maxIndex])  # 提取矩形坐标
            box = cv.boxPoints(rect)
            box = np.int0(box)
            angle = rect[2]
            cv.drawContours(cv_image,[box],0,(0,0,255),2)
            # 显示图像
            cv.imshow("Image", cv_image)
            twist = Twist()
            # 运动控制,左右转向和移动
            if center_x < screen_center - offset:
                twist.linear.x = 0.005
                twist.linear.y = 0.0
                twist.angular.z = 0.005
                print "turn left"
            elif screen_center - offset <= center_x <= screen_center + offset:
                if angle > -2.45:
                    twist.linear.x = 0.01
                    twist.linear.y = 0.0
                    twist.angular.z = -0.02
                    print "keep turn right"
                elif angle < -2.55:
                    twist.linear.x = 0.01
                    twist.linear.y = 0.0
                    twist.angular.z = 0.02
                    print "keep turn left"
                else:
                    twist.linear.x = 0.01
                    twist.linear.y = 0.0
                    twist.angular.z = 0.0
                    print "keep"
            elif center_x > screen_center + offset:
                twist.linear.x = 0.001
                twist.linear.y = 0.0
                twist.angular.z = -0.0015
                print "turn right"
            else:
                twist.linear.x = 0
                twist.linear.y = 0.0
                twist.angular.z = 0
            try:
                self.cmd_pub.publish(twist)
            except CvBridgeError as e:
                print e
            cv.waitKey(3)


if __name__ == '__main__':
    try:
        rospy.init_node("cv_bridge_test")
        rospy.loginfo("Starting cv_bridge_test node")
        image_converter()
        rospy.spin()

    except KeyboardInterrupt:
        print "Shutting down cv_bridge_test node."
        cv.destroyAllWindows()
